package cn.pzhu.services.admin;

import cn.pzhu.model.User;
import cn.pzhu.services.BaseServices;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dongp on 2016/4/24.
 */
public class UserServices extends BaseServices{

    public boolean ajaxAdd(String userID, String userName, String account, String password,Integer errorCount,
                        Integer maxCount, Integer roleValue) {

        // 检查是否重复
        User user = User.dao.findById(userID);
        if(user != null) {
            return false;
        }

        // 保存
        boolean result = new User().set("userName",userName).set("account",account).set("password",password)
                .set("errorCount",errorCount).set("maxCount",maxCount).set("roleVal", roleValue).save();

        return result;
    }

    public List ajaxQuery(String pageNumber, String pageSize, String search) {
        ArrayList arrts = new ArrayList();
        Map<String,Object> map = new HashMap<>();

        List<User> users = User.dao.find("select u.*,r.roleName from user u left join role r on u.roleVal = "
                + " r.roleValue where u.account like '%" + search + "%' limit " + pageNumber + "," + pageSize);
        arrts.add(users);

        User user = User.dao.findFirst("select count(*) total from user u where u.account like '%"+search+"%'");
        Long total = user.getLong("total").longValue();
        map.put("total", total);
        arrts.add(map);
        return arrts;
    }

    public boolean ajaxUpdate(String userID, String userName, String account, String password,Integer errorCount,
                              Integer maxCount, Integer roleValue) {

        boolean result = User.dao.findById(userID).set("userName",userName).set("account",account).set("password",password)
                .set("errorCount",errorCount).set("maxCount",maxCount).set("roleVal", roleValue).update();

        return result;
    }

    public boolean ajaxDel(String userID) {
        return User.dao.deleteById(userID);
    }
}
